<template>
  <div class="app-container">
    <el-form :inline="true" label-width="80px">
      <el-form-item label="音乐名称">
        <el-input
          v-model="queryParams.musicname"
          placeholder="音乐名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="success" size="mini" @click="handleInsert" v-hasPermi="['main:musicConfig:add']">添加</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="postList" @sort-change="sortChange">
      <el-table-column label="音乐名称" align="center" prop="musicname"/>
      <el-table-column label="文件类型" align="center" prop="filetype"/>
      <el-table-column label="展示序号" align="center" prop="sort" sortable="custom"/>
      <el-table-column label="作者" align="center" prop="author"/>
      <el-table-column label="备注" align="center" prop="remark" :show-tooltip-when-overflow="true"/>
      <el-table-column label="创建时间" align="center" prop="createtime" sortable="custom"/>
      <el-table-column label="播放" align="center" width="250">
        <template slot-scope="scope">
          <audio style="width: 220px; outline: none;" :src="scope.row.url" controls="controls"></audio>
        </template>
      </el-table-column>
      <el-table-column label="上/下架" align="center" prop="online">
        <template slot-scope="scope">
          <span v-if="scope.row.online===1">上架</span>
          <span v-else class="text-warning">下架</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" prop="idNo" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['main:musicConfig:edit']"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['main:musicConfig:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-dialog :title="title" :visible.sync="open" width="600px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="音乐名称" prop="musicname">
          <el-input v-model="form.musicname" placeholder="请输入音乐名称"/>
        </el-form-item>
        <el-form-item label="音乐文件" prop="url">
          <el-upload
            name="file"
            :action="uploadFile"
            ref="upload"
            :multiple="false"
            :show-file-list="true"
            :file-list="fileList"
            :headers="headers"
            :before-upload="beforeFileUpload"
            :on-success="handleFileSuccess"
            :on-change="handleFileChange"
            :on-error="handleFileError"
          >
            <el-input v-model="form.url" style="display: none;" placeholder="请输入音乐名称"/>
            <el-button size="small" type="primary" icon="el-icon-upload" plain="">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者"/>
        </el-form-item>
        <el-form-item label="展示序号" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="上/下架">
          <el-radio-group v-model="form.online" size="small">
            <el-radio label="1" border>上架</el-radio>
            <el-radio label="0" border>下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark"  type="textarea" placeholder="请输入备注内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native.prevent="submitForm">
          <span v-if="!addLoading">提 交</span>
          <span v-else>提 交 中...</span>
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getToken} from '@/utils/auth';
  import {Loading} from 'element-ui';
  import {deleteFile} from "@/api/common";
  import {listConfig, addConfig, putConfig,removeConfig} from "@/api/main/community/config";

  export default {
    data() {
      return {
        uploadFile: process.env.VUE_APP_BASE_API + "/common/aliyun/upload",
        open: false,
        addLoading: false,
        loading: false,
        daterange: undefined,
        postList: [],
        title: '',
        total: 0,
        fileList: [],
        loadingInstance: undefined,
        onlineOptions: [{"dictLabel": "上架", "dictValue": "1"}, {"dictLabel": "下架", "dictValue": "0"}],
        queryParams: {
          musicname: undefined,
          pageNum: 0,
          pageSize: 10,
          orderByColumn: 'createtime DESC'
        },
        form: {
          url: '',
          musicname: '',
          filetype: 'mp3',
          author: '',
          sort: undefined,
          remark: '',
          online: "0",
        },
        rules: {
          musicname: [
            {required: true, message: '请输入音乐名称', trigger: 'blur'},
            {max: 50, message: '长度最大为50个字符', trigger: 'blur'}
          ],
          url: [
            {required: true, message: '请选择MP3文件上传'}
          ],
          author:[
            {max: 50, message: '长度最大为50个字符', trigger: 'blur'}
          ],
          remark:[
            {max: 200, message: '长度最大为500个字符', trigger: 'blur'}
          ],
          sort:[
            {required: true, message: '请输入展示序号', trigger: 'blur'},
          ]
        },
        headers: {
          Authorization: 'Bearer ' + getToken()
        }
      }
    },
    created() {
      this.getList();
    },
    methods: {
      onlineFormat(row, column) {
        return this.selectDictLabel(this.onlineOptions, row[column.property]);
      },
      getList() {
        this.loading = true;
        listConfig(this.queryDateRange(this.queryParams, this.daterange)).then(response => {
          this.postList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      handleFileError() {
        this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          this.loadingInstance.close();
        });
      },
      handleFileChange(file, fileList) {
        if (fileList.length > 0) {
          //先做文件删除
          this.fileList = [fileList[fileList.length - 1]];
        }
      },
      handleFileSuccess(res) {
        this.form.url = res.urls[0];
        this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          this.loadingInstance.close();
        });
      },
      beforeFileUpload(file) {
        this.loadingInstance = Loading.service({fullscreen: true, text: '上传文件中。。。。', background: 'rgba(0, 0, 0, 0.1)'});
        const isAudio = file.type === "audio/mp3" || file.type === "audio/mpeg";
        if (!isAudio) {
          this.$message.error("上传文件只能是Mp3格式!");
        }
        if (this.form.url) {
          deleteFile(this.form.url).then(response => {
            console.log(response);
          });
        }
      },
      handleDelete(row) {
        let _this = this;
        this.$confirm(`确定要删除音乐名称[${row.musicname}]的记录?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info"
        }).then(function () {
          removeConfig({id: row.id, status: 0}).then(response => {
            _this.msgSuccess("删除成功");
            _this.getList();
          });
        }).catch(function (e) {
          console.log(e);
        });
      },
      handleInsert() {
        this.reset();
        this.title = '新增';
        this.open = true;
      },
      handleUpdate(row) {
        this.title = '编辑';
        this.form = {
          id: row.id,
          url: row.url,
          musicname: row.musicname,
          filetype: 'mp3',
          author: row.author,
          sort: row.sort,
          remark: row.remark,
          online: row.online + "",
          orderByColumn: 'createtime DESC'
        };
        this.fileList = [{name: row.musicname + '.mp3', url: row.url}];
        this.open = true;

      },
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      cancel() {
        this.open = false;
        this.reset();
      },
      reset() {
        this.form = {
          url: '',
          musicname: '',
          filetype: 'mp3',
          author: '',
          sort: undefined,
          remark: '',
          online: "0"
        };
        this.fileList = [];
        this.resetForm("form");
      },
      submitForm() {
        let _this = this;
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id) {
              putConfig(this.form).then(response => {
                this.msgSuccess("编辑成功");
                this.addLoading = false;
                this.open = false;
                this.getList();
              }).catch(function (e) {
                console.log(e);
                _this.addLoading = false;
              });
            } else {
              this.addLoading = true;
              addConfig(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.addLoading = false;
                this.open = false;
                this.getList();
              }).catch(function (e) {
                console.log(e);
                _this.addLoading = false;
              });
            }
          }
        });
      },
      sortChange(params) {
        if (params.prop === 'createtime') {
          let createtime = 'createtime';
          if (params.order === 'ascending') {
            this.queryParams.orderByColumn = createtime + ' ASC';
          } else {
            this.queryParams.orderByColumn = createtime + ' DESC';
          }
        } else if (params.prop === 'sort') {
          let sort = 'sort';
          if (params.order === 'ascending') {
            this.queryParams.orderByColumn = sort + ' ASC';
          } else {
            this.queryParams.orderByColumn = sort + ' DESC';
          }
        }
        this.getList();
      }
    }
  }
</script>

<style>

</style>
